package com.common.exception;

import cn.hutool.core.util.StrUtil;
import com.common.constant.LoggerConstant;
import com.common.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常处理类
 * @author YYQ
 *
 */
@ControllerAdvice
public class MyExceptionHandler {
	
	private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
	/** 用于判断/截取，哪些字段必填但未填返回的提示*/
	private static final String GET_MSG = "default message ";


	/**
	 * 全局异常返回json格式
	 * @param requset
	 * @param response
	 * @param ex
	 * @return
	 */
	@ExceptionHandler
	@ResponseBody
	public Result<?> handleAndReturnData(HttpServletRequest requset, HttpServletResponse response, Exception ex){
		logger.error(LoggerConstant.ERROR_MSG, ex);
		String exStr = ex.toString();
		int index = exStr.lastIndexOf(GET_MSG);
		if(index != -1){
			exStr = exStr.substring(index).replace(GET_MSG, StrUtil.EMPTY);
			return Result.error(Result.FAIL_MSG+"："+exStr);
		}
		return Result.error(Result.ERROR_MSG+"："+exStr);
	}




}
